package manageFriendshipsServlets;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sessions.requestFriendshipSession.FriendshipRequestSessionRemote;

public class SendFriendshipRequestServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertFriendshipRequest(request, response);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		insertFriendshipRequest(request, response);
	}
	
	private void insertFriendshipRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int idSender, idReceiver=0;
		Calendar now = Calendar.getInstance();
		Date date = now.getTime();	
		try {
			Context jndiCtx = new InitialContext();
			FriendshipRequestSessionRemote friendshipRequestRemote = (FriendshipRequestSessionRemote) jndiCtx
					.lookup("Progetto/FriendshipRequestSession/remote");
			idSender = (Integer)request.getSession().getAttribute("id");
			idReceiver = Integer.parseInt(request.getParameter("idReceiver"));
			//inserisce la richiesta di amicizia diretta nel db
			if(friendshipRequestRemote.insertFriendshipRequest(idSender, idReceiver, date, true, false)!=0)
				request.getSession().setAttribute("requestSent", "yes");
			else
				request.getSession().setAttribute("requestSent", "no");	
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Errore nella servlet");
		}
		response.sendRedirect("/ProgettoWeb/ResearchedUser.html?id=" + idReceiver);
	}

}
